package com.kust.smarthome.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kust.smarthome.web.model.Curtain;
import com.kust.smarthome.web.model.DeviceState;
import com.kust.smarthome.web.model.User;
import com.kust.smarthome.web.service.ICurtainService;
import com.kust.smarthome.web.service.IDeviceStateService;
import com.kust.smarthome.web.service.IUserService;
import com.kust.smarthome.web.vo.DeviceVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author iAuzre
 * @since 2021-06-28
 */

@RestController
@RequestMapping("/curtain")
@Api(value = "窗帘相关操作", tags = {"device-tag"})
public class CurtainController {

    @Resource
    private ICurtainService curtainService;

    @Resource
    private IDeviceStateService deviceStateService;

    @Resource
    private IUserService userService;

    /**
     * 通过用户信息获取对应设备列表
     * @param principal Security框架中获取登录用户的详细信息
     * @return 对应用户的窗帘设备表
     */
    @ApiOperation(value = "查询窗帘信息", notes = "根据用户信息查询对应用户窗帘信息")
    @GetMapping("")
    public List<Curtain> list(Principal principal) {
        User user = userService.getByUsername(principal.getName());
        return curtainService.getByUserId(user.getId());
    }

    @GetMapping("/getById")
    @ApiOperation(value = "getById", notes = "通过id获取对应设备")
    public Curtain getById(Integer id) {
        return curtainService.getById(id);
    }

    /**
     * 客户端请求一次开关窗帘,传给后端id,若该id对应的窗帘的状态为1(开)则将状态变为0,反之变为1
     * 同时,在状态表中插入对应状态
     * @param id curtain.getId()
     * @return 返回所有的窗帘属性,前端js代码成功收到响应之后将vue中的数据重新绑定即可
     */

    @GetMapping("/update")
    @Transactional
    @ApiOperation(value = "开关窗帘", notes = "根据窗帘id对窗帘进行开关操作")
    public List<Curtain> updateById(Principal principal, Integer id) {
        Curtain curtain = curtainService.getById(id);
        Integer state = 1;
        if (curtain.getState() == 1) {
            curtain.setState(0);
            state = 0;
        } else if (curtain.getState() == 0) {
            curtain.setState(1);
            state = 1;
        }

        curtainService.updateById(curtain);
        DeviceState deviceState = new DeviceState()
                .setDeviceId(id)
                .setTypeId(2)
                .setIsUpdate(0);
        //更改状态通知
        QueryWrapper<DeviceState> queryD = new QueryWrapper<>();//设备的Querywrapper
        queryD.eq("device_id",id);
        queryD.eq("type_id",2);
        deviceStateService.update(deviceState,queryD);

        User user = userService.getByUsername(principal.getName());
        return curtainService.getByUserId(user.getId());
    }

    /**
     * 网页端用户添加窗帘,方法中初始化一个窗帘对象并插入到数据表中
     * 若对窗帘数量有限制,前端可以添加一个判定条件,是否执行异步请求,同时后端也会做一次判定
     * 最大数量先定为3
     * @return 返回插入之后的窗帘列表
     */
    @GetMapping("/add")
    @Transactional
    @ApiOperation(value = "添加窗帘", notes = "根据用户信息以及操作者提供的窗帘id添加窗帘")
    public List<Curtain> addCurtain(Principal principal, DeviceVo deviceVo){

        User u = userService.getByUsername(principal.getName());//得到用户名字

        List<Curtain> list = curtainService.list();//查询当前所有窗帘，判断是否超过了三个

        LocalDateTime now = LocalDateTime.now();//得到现在时间

        if (list.size() < 3) {
            Curtain curtain = new Curtain()
                    .setId(deviceVo.getId())
                    .setUrl("")
                    .setContent("这是一个窗帘")
                    .setState(0)
                    .setCreated(now)
                    .setUserId(u.getId())
                    .setRoomId(deviceVo.getRoomId());
            curtainService.insert(curtain);
            list.add(curtain);

            QueryWrapper<Curtain> query = new QueryWrapper<>();
            query.eq("created",now);//查出当前创建的窗帘为了在设备表中插入
            Curtain c = curtainService.getOne(query);

            DeviceState deviceState = new DeviceState()
                    .setDeviceId(c.getId())
                    .setTypeId(2)
                    .setIsUpdate(0);
            //插入状态变更通知
            deviceStateService.insert(deviceState);
        }

        return list;
    }

    /**
     * 删除一个窗帘对象操作
     * 同时要删除其所对应的状态表
     * @param id 由客户端传入一个id
     * @return 当后端处理完删除操作之后返回当前数据库中的窗帘对象列表
     */
    @GetMapping("/deleteById")
    @Transactional
    @ApiOperation(value = "删除窗帘", notes = "根据窗帘id删除窗帘")
    public List<Curtain> deleteById(Integer id) {
        Curtain curtain = curtainService.getById(id);
        curtain.setUserId(-1);
        curtainService.updateById(curtain);
        QueryWrapper<DeviceState> query = new QueryWrapper<>();
        query.eq("device_id",curtain.getId());
        query.eq("type_id",2);
        deviceStateService.remove(query);

        return curtainService.list();
    }

}
